package plp.funcoo.expressions;

import plp.funcoo.environment.compilation.CompilationEnvironment;
import plp.funcoo.environment.compilation.Environment;
import plp.funcoo.environment.execution.ExecutionContext;
import plp.funcoo.environment.execution.ExecutionEnvironment;
import plp.funcoo.exceptions.ClassNotDeclared;
import plp.funcoo.exceptions.MethodAlreadDeclared;
import plp.funcoo.exceptions.MethodNotDeclared;
import plp.funcoo.exceptions.VarAlreadyDeclared;
import plp.funcoo.exceptions.VarNotDeclared;
import plp.funcoo.types.PrimitiveType;
import plp.funcoo.util.Type;
import plp.funcoo.value.BooleanValue;
import plp.funcoo.value.IntegerValue;

/**
 * Um objeto desta classe representa uma and Logica.
 */
public class ExpAnd extends BinaryExpression{

	/**
	 * Constroi uma Expressao de and logica  com as sub-expressoes
	 * especificadas.Estas devem ser tais que sua avaliacao resulta em
	 * <code>ValorBooleano</code>
	 *
	 * @param esq Expressao da esquerda
	 * @param dir Expressao da direita
	 */
	public ExpAnd(Expression left, Expression right){
		super(left, right, "&&");
			
	}
	
	@Override
	public ExecutionEnvironment evaluate(ExecutionEnvironment envi) throws VarNotDeclared, MethodNotDeclared, VarAlreadyDeclared, MethodAlreadDeclared {
		
		envi = getLeft().evaluate(envi); 
		BooleanValue l = (BooleanValue) ((ExecutionContext) envi).getValueAnalyzed();
		envi = getRight().evaluate(envi); 
		BooleanValue r = (BooleanValue) ((ExecutionContext) envi).getValueAnalyzed();
		((ExecutionContext) envi).setValueAnalyzed(new BooleanValue( l.getValue() && r.getValue() ));
		return envi;

	}

	@Override
	public Type getType(Environment envi) throws VarNotDeclared,
			ClassNotDeclared {
		return PrimitiveType.Type_BOOLEAN;
	}

	@Override
	protected boolean checkTypeTerminal(CompilationEnvironment envi)
			throws VarNotDeclared, ClassNotDeclared {
		return (getLeft().getType(envi)).isBoolean() && (getRight().getType(envi)).isBoolean();
	}

	@Override
	public Expression makeCopy() {
		return new ExpAnd(this.getLeft().makeCopy(), this.getRight().makeCopy());
	}
}
